<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>指标套餐评分管理</title>
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: 'Microsoft YaHei';
            background-color: #f5f5f5;
        }

        .container {
            height: 100vh;
            display: flex;
            flex-direction: column;
            padding: 10px 10px 0px 10px;
            box-sizing: border-box;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px;
            text-align: center;
        }

        .header h1 {
            margin: 0 0 10px 0;
            font-size: 28px;
            font-weight: 300;
        }

        .header p {
            margin: 0;
            opacity: 0.9;
            font-size: 16px;
        }

        .toolbar {
            padding: 15px 20px;
            background: white;
            border-bottom: 1px solid #e9ecef;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .main-content {
            flex: 1;
            padding-top: 10px;
            overflow: auto;
        }

        .score-table {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .el-table__body-wrapper {
            overflow-y: auto !important;
            overflow-x: auto;
        }


        .el-table__cell {
            padding: 0px 0px !important;
        }

        .el-table .cell {
            padding: 0px;
        }


        .el-table th.primary-header .cell {
            padding: 10px 0px;
            font-size: 13px;
            line-height: 1.3;
            height: 60px;
            color: #ffffff !important;
            background: linear-gradient(135deg, #00B0F0 0%, #00B0F0 100%) !important;
            text-align: center;
        }

        .el-table td.primary-header .cell {
            padding: 0px 0px;
            font-size: 13px;
            line-height: 1.3;
            background: #ffffff;

        }

        .el-table th.blue-header {
            background: linear-gradient(135deg, #00B0F0 0%, #00B0F0 100%) !important;
            color: #ffffff;
            text-align: center;
        }

        .el-table th.yellow-header {
            background: linear-gradient(135deg, #FFC000 0%, #FFC000 100%) !important;
            color: #ffffff;
            text-align: center;
        }

        .el-table th.red-header {
            background: linear-gradient(135deg, #E6B8B7 0%, #E6B8B7 100%) !important;
            color: #ffffff;
            text-align: center;
        }


        .el-table th.employee-cell {
            background-color: #CCCCCC !important;
            border-right: 1px solid #e8e8e8;
            color: #ffffff;
            font-weight: bold;
            text-align: center;
        }

        .el-table td.employee-cell {
            color: #606266;
            font-size: 12px;
        }

        .score-input {
            width: 100%;
        }

        .score-input .el-input__inner {
            border: 0px solid #00B0F0;
            text-align: center;
            height: 50px;
        }

        .score-input .el-input__inner:hover {
            border-bottom: 1px solid #00B0F0;
            text-align: center;
        }

        .el-textarea__inner {
            border: 0px solid #00B0F0;
        }

        .el-textarea__inner:hover {
            border-bottom: 1px solid #00B0F0;
        }

        .weight-info {
            font-size: 12px;
            color: #909399;
        }

        .weight-highlight {
            font-size: 12px;
            margin-top: 10px;
            color: #ffffff;
        }


        .summary-row {
            background-color: #f0f9ff;
            font-weight: bold;
            color: #409eff;
        }

        .completion-status {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 12px;
        }

        .status-completed {
            background-color: #f0f9ff;
            color: #67c23a;
        }

        .status-partial {
            background-color: #fdf6ec;
            color: #e6a23c;
        }

        .status-pending {
            background-color: #f4f4f5;
            color: #909399;
        }

        .action-buttons {
            display: flex;
            gap: 10px;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #909399;
        }

        .empty-state i {
            font-size: 48px;
            margin-bottom: 15px;
            display: block;
        }

        .required-remark {
            border: 2px solid #f56c6c !important;
        }

        .required-remark .el-textarea__inner {
            border-color: #f56c6c !important;
        }

        /* Smooth transitions for tab content */
        .el-tab-pane {
            transition: opacity 0.2s ease-in-out;
        }

        .score-table {
            transition: opacity 0.15s ease-in-out;
        }

        /* Loading animation */
        .el-icon-loading {
            animation: rotating 2s linear infinite;
        }

        @keyframes rotating {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }

        /* Prevent layout shift during loading */
        .empty-state {
            min-height: 200px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }
    </style>
</head>

<body>
    <div id="app">
        <div class="container">

            <div class="toolbar">
                <div>
                    <h3>指标套餐评分</h3>
                </div>
                <div class="action-buttons">
                    <el-button size="small" @click="clearAllScores">清空所有</el-button>
                    <el-button type="primary" size="small" @click="saveAllScores" :disabled="!hasAnyData">
                        保存所有得分
                    </el-button>
                </div>
            </div>

            <div class="main-content">
                <div v-if="packageList.length === 0" class="empty-state">
                    <i class="el-icon-folder-opened"></i>
                    <p>暂无指标套餐</p>
                    <p style="font-size: 12px;">请先到指标套餐管理页面创建套餐</p>
                </div>

                <div v-else>
                    <el-tabs v-model="activePackageTab" type="border-card" @tab-click="handleTabClick">
                        <el-tab-pane v-for="package in packageList" :key="package.id" :label="package.name"
                            :name="package.id">
                            <!-- Loading indicator -->
                            <div v-if="isDataLoading" class="empty-state">
                                <i class="el-icon-loading"></i>
                                <p>加载中...</p>
                            </div>

                            <!-- Empty state -->
                            <div v-else-if="getPackageUsers(package.id).length === 0" class="empty-state">
                                <i class="el-icon-user"></i>
                                <p>该套餐暂无用户</p>
                                <p style="font-size: 12px;">请先在套餐配置中添加用户</p>
                            </div>

                            <!-- Table content -->
                            <div v-else class="score-table" v-show="!isDataLoading">
                                <el-table :data="getTableData(package.id)" border style="width: 100%;height:100%;"
                                    :height="tableMaxHeight()" :key="'table_' + package.id"
                                    :row-key="row => row.employeeId || 'summary'" v-loading="isDataLoading">

                                    <el-table-column prop="employeeBU" label="BU" min-width="200" fixed="left"
                                        class-name="employee-cell">
                                        <template slot-scope="scope">
                                            {{scope.row.employeeBU }}
                                        </template>
                                    </el-table-column>
                                    <!-- 员工信息列 -->
                                    <el-table-column prop="employeeId" label="工号" width="80" fixed="left" align="center"
                                        class-name="employee-cell">
                                        <template slot-scope="scope">
                                            {{ scope.row.employeeId }}
                                        </template>
                                    </el-table-column>

                                    <el-table-column prop="employeeName" label="姓名" width="100" fixed="left"
                                        align="center" class-name="employee-cell">
                                        <template slot-scope="scope">
                                            {{ scope.row.employeeName }}
                                        </template>
                                    </el-table-column>

                                    <el-table-column prop="employeePosition" label="岗位" min-width="200"
                                        class-name="employee-cell">
                                        <template slot-scope="scope">
                                            {{scope.row.employeePosition }}
                                        </template>
                                    </el-table-column>

                                    <el-table-column prop="employeeHrType" label="人员类别" width="140"
                                        class-name="employee-cell">
                                        <template slot-scope="scope">
                                            {{ scope.row.employeeHrType }}
                                        </template>
                                    </el-table-column>

                                    <el-table-column prop="employeeDateJoin" label="入职时间" width="120" align="center"
                                        class-name="employee-cell">
                                        <template slot-scope="scope">
                                            {{formatDate(scope.row.employeeDateJoin) }}
                                        </template>
                                    </el-table-column>

                                    <el-table-column prop="employeeProbationDue" label="试用期到期" width="120"
                                        align="center" class-name="employee-cell">
                                        <template slot-scope="scope">
                                            {{formatDate(scope.row.employeeProbationDue) }}
                                        </template>
                                    </el-table-column>

                                    <!-- 因个人原因请假超过40小时原则不得奖金 -->
                                    <el-table-column prop="leaveOver40Hours" label="因个人原因请假超过40小时原则不得奖金" width="160"
                                        class-name="employee-cell">
                                        <template slot-scope="scope">
                                            <div class="weight-info" style="font-size: 11px;">{{
                                                scope.row.leaveOver40Hours || '-' }}</div>
                                        </template>
                                    </el-table-column>

                                    <!-- 警告单 (可编辑) -->
                                    <el-table-column prop="warningNotice" label="警告单" width="150"
                                        class-name="yellow-header" align="center">
                                        <template slot-scope="scope">
                                            <el-switch v-model="employeeWarnings[scope.row.employeeId]"
                                                inactive-color="#BBBBBB">
                                            </el-switch>
                                        </template>
                                    </el-table-column>

                                    <!-- 生产奖金最终发放金额 -->
                                    <el-table-column prop="productionBonusAmount" label="生产奖金最终发放金额" width="150"
                                        class-name="red-header">
                                        <template slot="header" slot-scope="scope">
                                            <el-tooltip class="item" effect="dark" content="按生产绩效结果和个人绩效结果的权重计算"
                                                placement="top">
                                                <div>
                                                    生产奖金最终发放金额
                                                    <i class="el-icon-info"></i>
                                                </div>
                                            </el-tooltip>
                                        </template>
                                        <template slot-scope="scope">
                                            <div class="weight-info" style="font-size: 11px;">{{
                                                scope.row.productionBonusAmount || '-' }}</div>
                                        </template>
                                    </el-table-column>

                                    <!-- 奖金基数 -->
                                    <el-table-column prop="bonusBase" label="奖金基数" width="100" class-name="red-header">
                                        <template slot-scope="scope">
                                            <div class="weight-info" style="font-size: 11px;">{{ scope.row.bonusBase
                                                || '-' }}</div>
                                        </template>
                                    </el-table-column>

                                    <!-- 生产关键绩效结果 -->
                                    <el-table-column prop="productionKpiResult" label="生产关键绩效结果" width="140"
                                        class-name="red-header">
                                        <template slot="header" slot-scope="scope">
                                            <el-tooltip class="item" effect="dark" content="通过员工对应的部门自动取HR填入的结果"
                                                placement="top">
                                                <div>
                                                    生产关键绩效结果
                                                    <i class="el-icon-info"></i>
                                                </div>
                                            </el-tooltip>
                                        </template>
                                        <template slot-scope="scope">
                                            {{scope.row.productionKpiResult || '-' }}
                                        </template>
                                    </el-table-column>

                                    <!-- 个人关键绩效结果 -->
                                    <el-table-column prop="personalKpiResult" label="个人关键绩效结果" width="140"
                                        class-name="red-header" align="center">
                                        <template slot="header" slot-scope="scope">
                                            <el-tooltip class="item" effect="dark"
                                                content="根据个人绩效指标权重及最终得分计算出个人绩效结果 + 个人绩效结果特殊调整项" placement="top">
                                                <div>
                                                    个人关键绩效结果
                                                    <i class="el-icon-info"></i>
                                                </div>
                                            </el-tooltip>
                                        </template>
                                        <template slot-scope="scope">
                                            {{calculateTotalScore(scope.row.employeeId, package.id) }}%
                                        </template>
                                    </el-table-column>

                                    <!-- 个人绩效结果特殊调整项 (可编辑) -->
                                    <el-table-column prop="personalPerformanceAdjustment" width="160"
                                        class-name="yellow-header" align="center">
                                        <template slot="header" slot-scope="scope">
                                            <el-tooltip class="item" effect="dark" content="可填正负值，若此格不为空，必须有备注才能提交"
                                                placement="top">
                                                <div>
                                                    个人绩效结果特殊调整项
                                                    <i class="el-icon-info"></i>
                                                </div>
                                            </el-tooltip>
                                        </template>
                                        <template slot-scope="scope">
                                            <el-input-number :controls="false"
                                                v-model="employeeAdjustments[scope.row.employeeId]" class="score-input"
                                                :min="-100" :max="100" :precision="1" size="mini"
                                                controls-position="right">
                                            </el-input-number>
                                        </template>
                                    </el-table-column>

                                    <!-- 备注列 -->
                                    <el-table-column label="备注" width="200" class-name="blue-header" align="center">
                                        <template slot-scope="scope">
                                            <el-input v-model="employeeRemarks[scope.row.employeeId]" type="textarea"
                                                :rows="2" placeholder="超过120分需填写备注" resize="none"
                                                :class="{ 'required-remark': calculateTotalScore(scope.row.employeeId, package.id) > 120 }"
                                                size="mini">
                                            </el-input>
                                        </template>
                                    </el-table-column>

                                    <!-- 动态生成指标列 -->
                                    <el-table-column v-for="indicator in getPackageIndicators(package.id)"
                                        :key="indicator.id" :label="indicator.chineseName"
                                        :class-name="'primary-header'" align="center">

                                        <template slot="header">
                                            <div>{{ indicator.chineseName }}</div>
                                            <div class="weight-highlight">Weight: {{ indicator.weight }}%</div>
                                        </template>

                                        <el-table-column v-for="subIndicator in indicator.selectedSubs"
                                            :key="subIndicator.id" :label="subIndicator.chineseName"
                                            :class-name="'primary-header'" align="center" min-width="150">

                                            <template slot="header">
                                                <div>{{ subIndicator.chineseName }}</div>
                                                <div class="weight-highlight">Weight: {{ subIndicator.weight }}%</div>
                                            </template>

                                            <template slot-scope="scope">
                                                <el-input-number :controls="false"
                                                    :value="getEmployeeScore(scope.row.employeeId, subIndicator.id)"
                                                    @change="updateEmployeeScore(scope.row.employeeId, subIndicator.id, $event)"
                                                    class="score-input" :min="0" :max="150" :precision="1" size="mini"
                                                    controls-position="right" placeholder="0">
                                                </el-input-number>
                                            </template>
                                        </el-table-column>
                                    </el-table-column>

                                </el-table>
                            </div>
                        </el-tab-pane>
                    </el-tabs>
                </div>
            </div>
        </div>
    </div>

    <script src="https://unpkg.com/vue@2/dist/vue.js"></script>
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script>
        new Vue({
            el: '#app',
            data() {
                return {
                    activePackageTab: '',
                    packageList: [],
                    packageData: {},
                    employeeScores: {},
                    employeeRemarks: {},
                    employeeWarnings: {},
                    employeeAdjustments: {},
                    // Cache table data for each package to reduce re-computation
                    packageTableDataCache: {},
                    // Track if data is loading to prevent flickering
                    isDataLoading: false
                }
            },
            computed: {
                hasAnyData() {
                    return Object.keys(this.employeeScores).length > 0;
                },

                currentPackageData() {
                    if (!this.activePackageTab) return null;
                    return this.packageData[this.activePackageTab] || null;
                },

                currentPackageUsers() {
                    return this.currentPackageData ? this.currentPackageData.users || [] : [];
                },

                currentPackageIndicators() {
                    return this.currentPackageData ? this.currentPackageData.indicators || [] : [];
                }
            },
            mounted() {
                this.loadPackageList();
                this.loadEmployeeScores();
                this.loadEmployeeRemarks();
                this.loadEmployeeWarnings();
                this.loadEmployeeAdjustments();

                // Debug information
                this.$nextTick(() => {
                    console.log('Loaded packages:', this.packageList);
                    console.log('Package data:', this.packageData);
                    if (this.packageList.length > 0) {
                        console.log('First package users:', this.getPackageUsers(this.packageList[0].id));
                    }
                });

                window.addEventListener('resize', () => { this.$forceUpdate() });
            },
            methods: {

                tableMaxHeight() {
                    // 计算表格最大高度：视窗高度 - 头部 - 标签页 - 其他元素
                    const headerHeight = 110; // 头部高度
                    const tabHeight = 80; // 标签页高度（包括padding和margin）
                    const height = window.innerHeight - headerHeight - tabHeight;
                    return Math.max(height, 200); // 确保最小高度
                },

                loadPackageList() {
                    const packages = [];
                    for (let i = 0; i < localStorage.length; i++) {
                        const key = localStorage.key(i);
                        if (key && key.startsWith('indicatorPackage_')) {
                            try {
                                const packageData = JSON.parse(localStorage.getItem(key));

                                // Load users from separate storage
                                const userKey = `packageUsers_${key}`;
                                let packageUsers = [];
                                const savedUsers = localStorage.getItem(userKey);
                                if (savedUsers) {
                                    try {
                                        packageUsers = JSON.parse(savedUsers);
                                    } catch (e) {
                                        console.warn('Failed to parse package users:', e);
                                    }
                                }

                                packages.push({
                                    id: key,
                                    name: packageData.name,
                                    sortOrder: packageData.sortOrder || 1,
                                    indicators: packageData.indicators || [],
                                    users: packageUsers
                                });

                                // Store in packageData for quick access
                                this.packageData[key] = {
                                    ...packageData,
                                    users: packageUsers
                                };

                                // Pre-cache table data to reduce computation during tab switching
                                this.packageTableDataCache[key] = packageUsers.map(user => ({
                                    isEmployee: true,
                                    employeeId: user.id,
                                    employeeName: user.name,
                                    employeeBU: user.department, // BU field
                                    employeePosition: user.position,
                                    employeeHrType: user.hrType || '-',
                                    employeeDateJoin: user.dateJoin || '-',
                                    employeeProbationDue: user.probationDueTime || '-'
                                }));
                            } catch (e) {
                                console.warn('Failed to parse package:', key);
                            }
                        }
                    }
                    this.packageList = packages.sort((a, b) => a.sortOrder - b.sortOrder);

                    if (this.packageList.length > 0 && !this.activePackageTab) {
                        this.activePackageTab = this.packageList[0].id;
                    }
                },

                getPackageUsers(packageId) {
                    const packageData = this.packageData[packageId];
                    return packageData ? packageData.users || [] : [];
                },

                getPackageIndicators(packageId) {
                    const packageData = this.packageData[packageId];
                    return packageData ? packageData.indicators || [] : [];
                },

                getTableData(packageId) {
                    // Return cached data if available
                    if (this.packageTableDataCache[packageId]) {
                        return this.packageTableDataCache[packageId];
                    }

                    const users = this.getPackageUsers(packageId);
                    const data = [];

                    // 添加员工行
                    users.forEach(user => {
                        data.push({
                            isEmployee: true,
                            employeeId: user.id,
                            employeeName: user.name,
                            employeeBU: user.department, // BU field
                            employeePosition: user.position,
                            employeeHrType: user.hrType || '-',
                            employeeDateJoin: user.dateJoin || '-',
                            employeeProbationDue: user.probationDueTime || '-'
                        });
                    });

                    // Cache the data for this package
                    this.packageTableDataCache[packageId] = data;
                    return data;
                },

                handleTabClick(tab) {
                    this.isDataLoading = true;
                    // Use requestAnimationFrame for smoother transitions
                    requestAnimationFrame(() => {
                        this.activePackageTab = tab.name;
                        setTimeout(() => {
                            this.isDataLoading = false;
                        }, 10);
                    });
                },

                getEmployeeScore(employeeId, indicatorId) {
                    if (!this.employeeScores[employeeId]) return 0;
                    return this.employeeScores[employeeId][indicatorId] || 0;
                },

                updateEmployeeScore(employeeId, indicatorId, value) {
                    if (!this.employeeScores[employeeId]) {
                        this.$set(this.employeeScores, employeeId, {});
                    }
                    this.$set(this.employeeScores[employeeId], indicatorId, value || 0);
                },

                calculateTotalScore(employeeId, packageId) {
                    const employeeScores = this.employeeScores[employeeId] || {};
                    const indicators = this.getPackageIndicators(packageId);
                    let totalScore = 0;

                    indicators.forEach(indicator => {
                        if (indicator.selectedSubs && indicator.selectedSubs.length > 0) {
                            let majorScore = 0;

                            indicator.selectedSubs.forEach(sub => {
                                const score = employeeScores[sub.id] || 0;
                                const weight = parseFloat(sub.weight) || 0;
                                majorScore += score * (weight / 100);
                            });

                            const majorWeight = parseFloat(indicator.weight) || 0;
                            totalScore += majorScore * (majorWeight / 100);
                        }
                    });

                    return Math.round(totalScore * 10) / 10;
                },

                clearAllScores() {
                    this.$confirm('确定要清空所有员工的得分吗？', '清空确认', {
                        confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
                    }).then(() => {
                        this.employeeScores = {};
                        this.employeeRemarks = {};
                        this.employeeWarnings = {};
                        this.employeeAdjustments = {};
                        this.$message.success('已清空所有得分、备注、警告单和调整项');
                    });
                },

                saveAllScores() {
                    // 检查超过120分的员工是否都有备注
                    let hasError = false;
                    const missingRemarks = [];

                    this.packageList.forEach(pkg => {
                        const users = this.getPackageUsers(pkg.id);
                        users.forEach(user => {
                            const totalScore = this.calculateTotalScore(user.id, pkg.id);
                            if (totalScore > 120 && (!this.employeeRemarks[user.id] || this.employeeRemarks[user.id].trim() === '')) {
                                hasError = true;
                                missingRemarks.push(`${user.name} (${pkg.name})`);
                            }
                        });
                    });

                    if (hasError) {
                        this.$message.error(`以下员工得分超过120分但未填写备注：${missingRemarks.join(', ')}`);
                        return;
                    }

                    localStorage.setItem('allEmployeeScores', JSON.stringify(this.employeeScores));
                    localStorage.setItem('allEmployeeRemarks', JSON.stringify(this.employeeRemarks));
                    localStorage.setItem('allEmployeeWarnings', JSON.stringify(this.employeeWarnings));
                    localStorage.setItem('allEmployeeAdjustments', JSON.stringify(this.employeeAdjustments));
                    this.$message.success('所有员工数据已保存');
                },

                loadEmployeeScores() {
                    const saved = localStorage.getItem('allEmployeeScores');
                    if (saved) {
                        this.employeeScores = JSON.parse(saved);
                    }
                },

                loadEmployeeRemarks() {
                    const saved = localStorage.getItem('allEmployeeRemarks');
                    if (saved) {
                        this.employeeRemarks = JSON.parse(saved);
                    }
                },

                loadEmployeeWarnings() {
                    const saved = localStorage.getItem('allEmployeeWarnings');
                    if (saved) {
                        this.employeeWarnings = JSON.parse(saved);
                    }
                },

                loadEmployeeAdjustments() {
                    const saved = localStorage.getItem('allEmployeeAdjustments');
                    if (saved) {
                        this.employeeAdjustments = JSON.parse(saved);
                    }
                },

                formatDate(dateString) {
                    if (!dateString || dateString === '-') return '-';
                    try {
                        const date = new Date(dateString);
                        if (isNaN(date.getTime())) return dateString; // Return original if invalid date
                        return date.toLocaleDateString('zh-CN', {
                            year: 'numeric',
                            month: '2-digit',
                            day: '2-digit'
                        });
                    } catch (e) {
                        return dateString; // Return original string if parsing fails
                    }
                }
            }
        });
    </script>
</body>

</html>